package com.gzx.bi.modular.screen.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.gzx.bi.modular.screen.config.BiScreenConfig;
import com.gzx.bi.modular.screen.constant.StatisticBIConstant;
import com.gzx.bi.modular.screen.entity.GzxStatisticBI;
import com.gzx.bi.modular.screen.mapper.GzxHtCallRecordMapper;
import com.gzx.bi.modular.screen.service.GzxHtCallRecordService;
import com.gzx.bi.modular.screen.util.ScreenDateUtils;
import com.gzx.bi.modular.screen.util.ScreenUtils;
import com.gzx.bi.modular.screen.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * bi报表服务实现类
 *
 * @author xbl
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxHtCallRecordServiceImpl implements GzxHtCallRecordService {

    //话单mapper
    private final GzxHtCallRecordMapper htCallRecordMapper;

    @Autowired
    private BiScreenConfig biScreenConfig;

    @DS("tjzy-async")
    @Override
    public GzxStatisticBIVo mergeTodayCall(List<GzxStatisticBI> list) {
        //报表
        GzxStatisticBIVo vo = new GzxStatisticBIVo();
        //今日通话分析
        GzxTodayCallVo todayCallVo = new GzxTodayCallVo();

        //所有的客户地区
        List<GzxCommonVo> areaList = new ArrayList<>();
        for (GzxStatisticBI bi : list) {
            JSONObject json = JSON.parseObject(bi.getBiResult());
            List<GzxCommonVo> areaVo = JSON.parseArray(json.getString("customerArea"), GzxCommonVo.class);
            areaList.addAll(areaVo);
            //当天的四个数字
            String currentDate = bi.getBiMonth();
            if (ScreenDateUtils.getMonthDay().equals(currentDate)) {
                todayCallVo.setLineNum(json.getInteger("lineNum"));
                todayCallVo.setCustomerAreaNum(json.getInteger("customerAreaNum"));
                todayCallVo.setCallNum(json.getInteger("callNum"));
                todayCallVo.setTotalCallDuration(json.getInteger("totalCallDuration"));
            }
        }

        List<GzxCommonVo> areaResult = areaList.stream().collect(Collectors.groupingBy(GzxCommonVo::getName, Collectors.collectingAndThen(Collectors.toList(), group -> {
            GzxCommonVo r = new GzxCommonVo();
            r.setName(group.getFirst().getName());
            r.setValue(group.stream().mapToInt(GzxCommonVo::getValue).sum());
            return r;
        }))).values().stream().toList();

        //计算百分比
        int total = areaResult.stream().mapToInt(GzxCommonVo::getValue).sum();
        for (GzxCommonVo area : areaResult) {
            area.setRate((total == 0) ? 0 : Double.parseDouble(String.format("%.2f", (double) area.getValue() / total)));
        }

        todayCallVo.setCustomerArea(areaResult);
        vo.setBiResult(JSON.toJSONString(todayCallVo));
        log.info("今日通话分析 合并之后的结果 -> {} ", vo);
        return vo;
    }

    //合并主报表
    @DS("tjzy-async")
    @Override
    public GzxStatisticBIVo mergeMain(List<GzxStatisticBI> list) {
        GzxStatisticBIVo vo = new GzxStatisticBIVo();
        //主报表假数据
        GzxMainBIVo mainBIVo = new GzxMainBIVo();
        mainBIVo.setHistoryMediationSuccessCaseTotal(biScreenConfig.getHistoryMediationSuccessCaseTotal());
        mainBIVo.setHistoryMediationSuccessRate(biScreenConfig.getHistoryMediationSuccessRate());
        mainBIVo.setCaseMoneyStr(ScreenUtils.convertMoney(biScreenConfig.getCaseMoney()));
        //用于计算统计数量
        List<GzxMainBIVo> mainList = new ArrayList<>();
        //团队人均呼叫量排行榜
        List<GzxOfficeCallRankVo> teamAgentVoList = new ArrayList<>();
        //坐席呼叫量排行榜
        List<GzxAgentCallRankVo> agentCallRankVoList = new ArrayList<>();
        //客户分布地区
        List<GzxAreaVo> areaVoList = new ArrayList<>();

        //把每天的json存到list里
        for (GzxStatisticBI bi : list) {
            GzxMainBIVo biVo = JSON.parseObject(bi.getBiResult(), GzxMainBIVo.class);
            mainList.add(biVo);
            teamAgentVoList.addAll(biVo.getTeamAgentVoList());
            agentCallRankVoList.addAll(biVo.getAgentCallRankVoList());
            areaVoList.addAll(biVo.getAreaVoList());
        }

        //接通总数
        int callTotal = mainList.stream().mapToInt(GzxMainBIVo::getCallTotal).sum();
        mainBIVo.setCallTotal(callTotal);
        //接通总时长
        double totalCallDuration = mainList.stream().mapToDouble(GzxMainBIVo::getTotalCallDuration).sum();
        mainBIVo.setTotalCallDuration(totalCallDuration);
        //呼出总数
        int callOutgoingTotal = mainList.stream().mapToInt(GzxMainBIVo::getCallOutgoingTotal).sum();
        mainBIVo.setCallOutgoingTotal(callOutgoingTotal);
        //活跃坐席数
        int activeAgentTotal = mainList.stream().mapToInt(GzxMainBIVo::getActiveAgentTotal).max().orElse(0);
        mainBIVo.setActiveAgentTotal(activeAgentTotal);
        //人均载案量
        int averageCallTotal = mainList.stream().mapToInt(GzxMainBIVo::getAverageCallTotal).sum();
        mainBIVo.setAverageCallTotal(averageCallTotal);

        //团队人均呼叫量排行榜：所有调解中心|职场|团队|部门 按照deptId分组并且sum（人均呼叫量）
        List<GzxOfficeCallRankVo> teamAgentResult = new ArrayList<>(teamAgentVoList.stream().filter(v -> v.getDeptId() != null && !ObjectUtils.isEmpty(v.getDeptId()) && v.getDeptName() != null && !ObjectUtils.isEmpty(v.getDeptName())).collect(Collectors.groupingBy(GzxOfficeCallRankVo::getDeptId, Collectors.collectingAndThen(Collectors.toList(), group -> {
            GzxOfficeCallRankVo r = new GzxOfficeCallRankVo();
            r.setDeptId(group.getFirst().getDeptId());
            r.setDeptName(group.getFirst().getDeptName());
            r.setCallTotalRank(group.stream().mapToInt(GzxOfficeCallRankVo::getCallTotalRank).sum());
            return r;
        }))).values().stream().toList());
        int minCallTotalRank = teamAgentResult.stream().mapToInt(GzxOfficeCallRankVo::getCallTotalRank).min().orElse(0);
        //生成比 minCallTotalRank 小1000左右的随机数
        teamAgentResult.add(new GzxOfficeCallRankVo(ScreenUtils.generateUUID(), "北京调解中心", ScreenUtils.generateRandomNumber(minCallTotalRank)));
        teamAgentResult.add(new GzxOfficeCallRankVo(ScreenUtils.generateUUID(), "济南调解中心", ScreenUtils.generateRandomNumber(minCallTotalRank)));
        teamAgentResult.add(new GzxOfficeCallRankVo(ScreenUtils.generateUUID(), "海南调解中心", ScreenUtils.generateRandomNumber(minCallTotalRank)));
        teamAgentResult.add(new GzxOfficeCallRankVo(ScreenUtils.generateUUID(), "盐城调解中心", ScreenUtils.generateRandomNumber(minCallTotalRank)));
        teamAgentResult.add(new GzxOfficeCallRankVo(ScreenUtils.generateUUID(), "廊坊调解中心  ", ScreenUtils.generateRandomNumber(minCallTotalRank)));

        //数字超过10w的拼成10w，不到10w的就是几千
        for (GzxOfficeCallRankVo officeCallRankVo : teamAgentResult) {
            officeCallRankVo.setCallTotalRankStr(ScreenUtils.formatNumber(officeCallRankVo.getCallTotalRank()));
        }
        mainBIVo.setTeamAgentVoList(teamAgentResult);

        //客户呼叫量排行榜：根据agentId分组，sum(呼叫量)
        List<GzxAgentCallRankVo> agentCallRankResult = agentCallRankVoList.stream().collect(Collectors.groupingBy(GzxAgentCallRankVo::getAgentId, Collectors.collectingAndThen(Collectors.toList(), group -> {
                    GzxAgentCallRankVo r = new GzxAgentCallRankVo();
                    r.setAgentId(group.getFirst().getAgentId());
                    r.setAgentName(group.getFirst().getAgentName());
                    r.setDeptId(group.getFirst().getDeptId());
                    r.setDeptName(group.getFirst().getDeptName());
                    r.setCallTotalRank(group.stream().mapToInt(GzxAgentCallRankVo::getCallTotalRank).sum());
                    return r;
                }))).values().stream()
                .sorted(Comparator.comparingInt(GzxAgentCallRankVo::getCallTotalRank).reversed())
                .limit(StatisticBIConstant.AGENT_NUM)
                .toList();
        //数字超过10w的拼成10w，不到10w的就是几千
        for (GzxAgentCallRankVo agentCallRankVo : agentCallRankResult) {
            agentCallRankVo.setCallTotalRankStr(ScreenUtils.formatNumber(agentCallRankVo.getCallTotalRank()));
        }
        mainBIVo.setAgentCallRankVoList(agentCallRankResult);

        //客户分布地区: 根据地区分组，sum（地区人数）
        List<GzxAreaVo> areaResult = areaVoList.stream().collect(Collectors.groupingBy(GzxAreaVo::getAreaName, Collectors.collectingAndThen(Collectors.toList(), group -> {
            GzxAreaVo r = new GzxAreaVo();
            r.setAreaName(group.getFirst().getAreaName());
            r.setAreaCustomerNum(group.stream().mapToInt(GzxAreaVo::getAreaCustomerNum).sum());
            return r;
        }))).values().stream().toList();
        //地区名称为空的都去掉
        areaResult = areaResult.stream().filter(v -> !ObjectUtils.isEmpty(v.getAreaName())).toList();
        mainBIVo.setAreaVoList(areaResult);

        vo.setBiResult(JSON.toJSONString(mainBIVo));
        log.info("主报表 合并之后的结果 -> {} ", vo);
        return vo;
    }

}
